package com.yfp.operation.controller;

import com.alibaba.fastjson2.JSONObject;
import com.yfp.common.core.domain.R;
import com.yfp.operation.domain.WxGroupChat;
import com.yfp.operation.domain.WxGroupMember;
import com.yfp.operation.service.WxGroupChatService;
import com.yfp.operation.service.WxGroupConfigService;
import com.yfp.operation.service.WxGroupMemberService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.error.WxErrorException;
import me.chanjar.weixin.cp.api.WxCpService;
import me.chanjar.weixin.cp.bean.external.WxCpGroupJoinWayInfo;
import me.chanjar.weixin.cp.bean.external.WxCpGroupJoinWayResult;
import me.chanjar.weixin.cp.bean.external.WxCpUserExternalGroupChatInfo;
import me.chanjar.weixin.cp.bean.external.WxCpUserExternalGroupChatList;
import me.chanjar.weixin.cp.bean.external.contact.ExternalContact;
import me.chanjar.weixin.cp.bean.external.contact.WxCpExternalContactInfo;
import me.chanjar.weixin.cp.bean.message.WxCpAppChatMessage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Arrays;
import java.util.List;

/**
 * @Description: 企业微信
 *
 * @CreateDate: 2024/7/5 19:15
 * @UpdateUser:
 * @UpdateDate: 2024/7/5 19:15
 * @UpdateRemark: 暂无修改
 * @Version: 1.0
 */
@RestController
@RequestMapping("/wxCp")
@Tag(name = "企业微信")
@Slf4j
public class WxCpController {
    @Autowired
    private WxCpService wxCpService;
    @Autowired
    private WxGroupChatService wxGroupChatService;
    @Autowired
    private WxGroupConfigService wxGroupConfigService;
    @Autowired
    private WxGroupMemberService wxGroupMemberService;

    @Operation(summary = "查询群列表")
    @GetMapping("/list")
    public R<List<WxGroupChat>> list(WxGroupChat wxGroupChat) throws WxErrorException {
        // 获取外部联系人的群组ID列表
        wxGroupChat.setStatus(1);
        List<WxGroupChat> list = wxGroupChatService.findList(wxGroupChat);
        return R.ok(list);
    }

    @Operation(summary = "测试-获取微信群二维码")
    @PostMapping("/qrCode")
    public R<Void> qrCode() throws WxErrorException {
        // 获取外部联系人的群组ID列表
        WxCpGroupJoinWayInfo.JoinWay joinWay = new WxCpGroupJoinWayInfo.JoinWay();
        joinWay.setRemark("测试点位");
        joinWay.setScene(2);
        joinWay.setAutoCreateRoom(1);
        joinWay.setRoomBaseName("");
        joinWay.setRoomBaseId(1);
        joinWay.setState("测试点位群");
        joinWay.setChatIdList(Arrays.asList("wrezA7DwAAbo1IwHIJDfEqOwE4nw_KOQ"));
        WxCpGroupJoinWayInfo wxCpGroupJoinWayInfo = new WxCpGroupJoinWayInfo();
        wxCpGroupJoinWayInfo.setJoinWay(joinWay);
        WxCpGroupJoinWayResult wxCpUserExternalGroupChatList = wxCpService.getExternalContactService().addJoinWay(wxCpGroupJoinWayInfo);
        log.info("wxCpUserExternalGroupChatList: {}", JSONObject.toJSONString(wxCpUserExternalGroupChatList));
        WxCpGroupJoinWayInfo joinWay1 = wxCpService.getExternalContactService().getJoinWay(wxCpUserExternalGroupChatList.getConfigId());
        log.info("joinWay1: {}", JSONObject.toJSONString(joinWay1));
        return R.ok();
    }

    @Operation(summary = "测试-同步微信群列表")
    @PostMapping("/syncGroupChat")
    @Transactional
    public R<Void> syncGroupChat() throws WxErrorException {
        // 获取外部联系人的群组ID列表
        WxCpUserExternalGroupChatList wxCpUserExternalGroupChatList = wxCpService.getExternalContactService().listGroupChat(1000, null, 0, null);
        for (WxCpUserExternalGroupChatList.ChatStatus chatStatus : wxCpUserExternalGroupChatList.getGroupChatList()) {
            System.err.println( chatStatus.getChatId());
            log.info("wxCpUserExternalGroupChatList：{}", JSONObject.toJSONString(wxCpUserExternalGroupChatList));
            // 是否已存库
            WxGroupChat wxGroupChat = wxGroupChatService.getById(chatStatus.getChatId());
            WxCpUserExternalGroupChatInfo groupChatInfo = wxCpService.getExternalContactService().getGroupChat(chatStatus.getChatId(), 1);
            WxCpUserExternalGroupChatInfo.GroupChat groupChat = groupChatInfo.getGroupChat();
            if (null == wxGroupChat){
                wxGroupChat = new WxGroupChat();
                log.info("WxCpUserExternalGroupChatInfo: {}", JSONObject.toJSONString(groupChatInfo));
                log.info("groupChatId: {}, groupName: {}", groupChatInfo.getGroupChat().getChatId(), groupChatInfo.getGroupChat().getName());
                wxGroupChat.setGroupChatId(groupChat.getChatId());
                wxGroupChat.setGroupChatName(groupChat.getName());
                wxGroupChat.setNotice(groupChat.getNotice());
                wxGroupChat.setCreateTime(groupChat.getCreateTime());
                wxGroupChat.setOwner(groupChat.getOwner());
                wxGroupChat.setAdminList(JSONObject.toJSONString(groupChat.getAdminList()));
                wxGroupChatService.add(wxGroupChat);
            } else{
                wxGroupChat.setGroupChatId(groupChat.getChatId());
                wxGroupChat.setGroupChatName(groupChat.getName());
                wxGroupChat.setNotice(groupChat.getNotice());
                wxGroupChat.setCreateTime(groupChat.getCreateTime());
                wxGroupChat.setOwner(groupChat.getOwner());
                wxGroupChat.setAdminList(JSONObject.toJSONString(groupChat.getAdminList()));
                wxGroupChatService.edit(wxGroupChat);
            }
            wxGroupMemberService.delByGroupChatId(groupChat.getChatId());
            // 同步群数据
            String cursor = null;
            for (WxCpUserExternalGroupChatInfo.GroupMember groupMember : groupChat.getMemberList()) {
                log.info("userId：{}， groupChatId：{}", groupMember.getUserId(), groupChat.getChatId());
                // 获取用户消息
                WxGroupMember wxGroupMember = new WxGroupMember();
                if (groupMember.getType() == 2){
                    WxCpExternalContactInfo externalContactInfo = null;
                    try {
                        externalContactInfo = wxCpService.getExternalContactService().getContactDetail(groupMember.getUserId(), cursor);
                        cursor = externalContactInfo.getNextCursor();
                        ExternalContact wxCpUser = externalContactInfo.getExternalContact();
                        log.info("微信用户消息：{}", JSONObject.toJSONString(wxCpUser));
                        wxGroupMember.setGender(wxCpUser == null || wxCpUser.getGender()== null? "0" : wxCpUser.getGender()+"");
                        wxGroupMember.setAvatar(wxCpUser == null ? "":wxCpUser.getAvatar());
                    } catch (Exception e){
                        log.info(e.getMessage());
                    }
                }
                wxGroupMember.setUserId(groupMember.getUserId());
                wxGroupMember.setGroupNickname(groupMember.getGroupNickname());
                wxGroupMember.setName(groupMember.getName());
                wxGroupMember.setType(groupMember.getType());
                wxGroupMember.setJoinTime(groupMember.getJoinTime());
                wxGroupMember.setUnionId(groupMember.getUnionId());
                wxGroupMember.setJoinScene(groupMember.getJoinScene());
                wxGroupMember.setGroupChatId(groupChat.getChatId());
                wxGroupMemberService.add(wxGroupMember);

//                WxGroupMember wxGroupMember = wxGroupMemberService.getByIdAndGroupChatId(groupMember.getUserId(), groupChat.getChatId());
//                if (null == wxGroupMember){
//                    // 获取用户消息
//                    wxGroupMember = new WxGroupMember();
//                    if (groupMember.getType() == 2){
//                        WxCpExternalContactInfo externalContactInfo = null;
//                        try {
//                            externalContactInfo = wxCpService.getExternalContactService().getContactDetail(groupMember.getUserId(), cursor);
//                            cursor = externalContactInfo.getNextCursor();
//                            ExternalContact wxCpUser = externalContactInfo.getExternalContact();
//                            log.info("微信用户消息：{}", JSONObject.toJSONString(wxCpUser));
//                            wxGroupMember.setGender(wxCpUser == null || wxCpUser.getGender()== null? "0" : wxCpUser.getGender()+"");
//                            wxGroupMember.setAvatar(wxCpUser == null ? "":wxCpUser.getAvatar());
//                        } catch (Exception e){
//                            log.info(e.getMessage());
//                        }
//                    }
//                    wxGroupMember.setUserId(groupMember.getUserId());
//                    wxGroupMember.setGroupNickname(groupMember.getGroupNickname());
//                    wxGroupMember.setName(groupMember.getName());
//                    wxGroupMember.setType(groupMember.getType());
//                    wxGroupMember.setJoinTime(groupMember.getJoinTime());
//                    wxGroupMember.setUnionId(groupMember.getUnionId());
//                    wxGroupMember.setJoinScene(groupMember.getJoinScene());
//                    wxGroupMember.setGroupChatId(groupChat.getChatId());
//                    wxGroupMemberService.add(wxGroupMember);
//                } else {
//                    wxGroupMember.setGroupNickname(groupMember.getGroupNickname());
//                    wxGroupMember.setName(groupMember.getName());
//                    wxGroupMember.setType(groupMember.getType());
//                    wxGroupMember.setJoinTime(groupMember.getJoinTime());
//                    wxGroupMember.setUnionId(groupMember.getUnionId());
//                    wxGroupMember.setJoinScene(groupMember.getJoinScene());
//                    wxGroupMemberService.edit(wxGroupMember);
//                }
            }
            log.info("用户人数：{}", groupChat.getMemberList().size());
        }
        return R.ok();
    }

    @Operation(summary = "测试-获取微信群列表")
    @PostMapping("/createGraup")
    public R<Void> createGraup() throws WxErrorException {
        WxCpAppChatMessage wxCpAppChatMessage = new WxCpAppChatMessage();
        wxCpAppChatMessage.setChatId("12312123");
        wxCpAppChatMessage.setTitle("test");
        wxCpAppChatMessage.setContent("测试自动建群，自动发送消息");
        wxCpAppChatMessage.setSafe(false);
        wxCpAppChatMessage.setMsgType("text");
        wxCpService.getChatService().sendMsg(wxCpAppChatMessage);
        return R.ok();
    }
}
